package cn.iune.config;

import java.util.List;
import java.util.Map;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.justep.baas.Utils;

import cn.iune.backcenter.author.SaOporg;

@Service
public class SecurityService {
	  
	
	public static Subject getCurrentUser(){
		Subject subject = SecurityUtils.getSubject();
		if(!subject.isAuthenticated()){
			//System.out.println("SecurityService.getCurrentUser-->用户没有登录！");
		}
		return subject;
	}

	public static boolean hasRole(String roleIdentifier){
		return getCurrentUser().hasRole(roleIdentifier);
	}

	public static Session getCurrentSession(){
		Session session = getCurrentUser().getSession();
//		System.out.println("----------------------shiro sessionid-->"+session.getId());
		return session;
	}
	
	/*
	public static void setCurrentUser(Subject subject){
		getCurrentSession().setAttribute("currentUser",subject);
	}
	*/

	public static String getCurrentLoginName(){
		if (null != getCurrentPerson()) {
			return getCurrentPerson().getString("sLoginName");
		}else{
			return null;
		}
	}

	
	public static String getCurrentAppId(){
		String obj = (String) getCurrentSession().getAttribute("appId");
		if(obj==null){
			return null;
		}else{
			return obj;
		}
	}
	
	public static void setCurrentAppId(String appId){
		getCurrentSession().setAttribute("appId",appId);
	}

	
	public static String getCurrentAppName(){
		String obj = (String) getCurrentSession().getAttribute("appName");
		if(obj==null){
			return null;
		}else{
			return obj;
		}
	}
	
	public static void setCurrentAppName(String appName){
		getCurrentSession().setAttribute("appName",appName);
	}

	
	public static SaOporg getCurrentPsm(){
		Object obj = getCurrentSession().getAttribute("currentPsm");
		if(obj==null){
			return null;
		}else{
			SaOporg saOporg = (SaOporg) obj;
			return saOporg;
		}
	}
	
	public static void setCurrentPsm(SaOporg saOporg){
		getCurrentSession().setAttribute("currentPsm",saOporg);
	}
	
	public static SaOporg getCurrentOgn(){
		Object obj = getCurrentSession().getAttribute("currentOgn");
		if(obj==null){
			return null;
		}else{
			SaOporg saOporg = (SaOporg) obj;
			return saOporg;
		}
	}
	
	public static void setCurrentOgn(SaOporg saOporg){
		getCurrentSession().setAttribute("currentOgn",saOporg);
	}
	
	public static List<SaOporg> getCurrentPsmList(){
		Object obj = getCurrentSession().getAttribute("currentPsmList");
		if(obj==null){
//			log.info("当前组织关系为空！");
			return null;
		}else{
			@SuppressWarnings("unchecked")
			List<SaOporg> saOporgList = (List<SaOporg>) obj;
			return saOporgList;
		}
	}
	
	public static void setCurrentPsmList(List<SaOporg> saOporgList){
		getCurrentSession().setAttribute("currentPsmList",saOporgList);
	}
	
	public static List<SaOporg> getCurrentOgnList(){
		Object obj = getCurrentSession().getAttribute("currentOgnList");
		if(obj==null){
//			log.info("当前组织为空！");
			return null;
		}else{
			@SuppressWarnings("unchecked")
			List<SaOporg> saOporgList = (List<SaOporg>) obj;
			return saOporgList;
		}
	}
	
	public static void setCurrentOgnList(List<SaOporg> saOporgList){
		getCurrentSession().setAttribute("currentOgnList",saOporgList);
	}

	public static Object getCurrentFactory(){
		return getCurrentSession().getAttribute("currentFactory");
	}

	//当前门店
//	public static void setCurrentFactory(FileFactory currentFactory){
	public static void setCurrentFactory(Object currentFactory){
		getCurrentSession().setAttribute("currentFactory",currentFactory);
	}

	/*
	public static SaOpperson getCurrentPerson(){
		Object obj = getCurrentSession().getAttribute("person");
		if(obj==null){
			return null;
		}else{
			SaOpperson person =  (SaOpperson) obj;
        	person.setsPassword("****");
			return person;
		}
	}
	*/
	
	public static JSONObject getCurrentPerson(){
		Object obj = getCurrentSession().getAttribute("person");
		if(obj==null){
			return null;
		}else{
			JSONObject person =  (JSONObject) obj;
			return person;
		}
	}
	
	public static void setCurrentPerson(Object person){
		getCurrentSession().setAttribute("person",person);
	}
	
	/*
	public static JSONObject getCurrentPersonSimple(){
		SaOpperson person = SecurityService.getCurrentPerson();
		if (null != person) {
			JSONObject data = new JSONObject();
			data.put("sID", person.getsID());
			data.put("sCode", person.getsCode());
			data.put("sName", person.getsName());
			data.put("sLoginName", person.getsLoginName());
			data.put("sCreatorFID", person.getsCreatorFID());
			//log.info("person.getImages()-->"+person.getImages());
			data.put("images", person.getImages());
			
			JSONObject json = new JSONObject();
			json.put("statusCode", 0);
			json.put("person", data);

			return json;
		}else{
			JSONObject json = new JSONObject();
			json.put("statusCode", -1);
			
			return json;
		}
	}
	*/
	
//	@SuppressWarnings("unchecked")
//	public static Set<String> getRealmRoles(){
//		return (Set<String>) getCurrentSession().getAttribute("realmRoles");
//	}
//	
//	public static void setRealmRoles(Set<String> realmRoles){
//		getCurrentSession().setAttribute("realmRoles", realmRoles);
//	}

	@SuppressWarnings("unchecked")
	public static List<String> getTreeNavigation(){
		return (List<String>) getCurrentSession().getAttribute("treeNavigation");
	}
	
	public static void setTreeNavigation(List<String> ids){
		getCurrentSession().setAttribute("treeNavigation", ids);
	}
	
	@SuppressWarnings("unchecked")
	public static String getDataAccessPerm(String url){
//		System.out.println("url-->"+url);
		String dataAccessPerm = "N";
		Map<String,String> map =  (Map<String, String>) getCurrentSession().getAttribute("dataAccessUrls");
		
//		for(Map.Entry<String, String> entry : map.entrySet()){
//			log.info("Key = " + entry.getKey() + ", Value = " + entry.getValue());  
//		}
		
		if(map!=null && map.containsKey(url)){
			//存在
			dataAccessPerm = map.get(url);
//			System.out.println("存在-->"+dataAccessPerm);
		}
		
		return dataAccessPerm;
	}
	
	public static JSONObject addDataAccessPerm(JSONObject data){
		String concept = data.getString("concept");
		if(concept==null) {
			System.out.println("concept-->"+concept);
			return data;
		}else {
			//this.filters = [{"name":"filter1","filter":"sss"},{"name":"filter2","filter":"sss2"}];
			JSONArray filterList = data.getJSONArray("filters");
			//保证查询出来的结果是当前公司，不能显示其他公司的数据
			JSONObject json = new JSONObject();
//			String enterpriseNo = getCurrentOgn().getsFID();
			json.put("filter", concept+".enterpriseNo='"+getCurrentOgn().getsFID()+"'");
			filterList.add(json);
			//判断是否具有只查看自己的条件
			String url = data.getString("url");
			if(url==null) {
				System.out.println("url-->"+url);
			}else {
				if("Y".equals(getDataAccessPerm(url))){
//					String userId = getCurrentPerson().getsID();
					json = new JSONObject();
					json.put("filter", concept+".userId='"+getCurrentPerson().getString("userId")+"'");
					filterList.add(json);
				}
			}
//			System.out.println("addDataAccessPerm.filterList-->"+filterList.toJSONString());
			data.put("filters", filterList);
		}
//		System.out.println("data-->"+data.toJSONString());
		return data;
	}
	
	//翻译函数
	public static JSONObject translateFun(JSONObject data){
		//拷贝对象
		data = JSONObject.parseObject(data.toJSONString());
		//增加登录信息
		//缺省值
		JSONArray defaultValues = data.getJSONArray("defaultValues");
		//循环缺省值（多行）
		for(int i=0;i<defaultValues.size();i++) {
			JSONObject rowValue = defaultValues.getJSONObject(i);
			//循环列
			//循环缺省值（单行）
			for(String col: rowValue.keySet()) {
				//System.out.println("controller.defaultValues-->>"+col+":"+rowValue.get(col));
				if(":getCurrentDate()".equals(rowValue.get(col))) {
					rowValue.put(col, Utils.getCurrentDate());
				}
				if(":getCurrentPsmFID()".equals(rowValue.get(col))) {
					rowValue.put(col, SecurityService.getCurrentPsm().getsFID());
				}
				if(":getCurrentPsmFName()".equals(rowValue.get(col))) {
					rowValue.put(col, SecurityService.getCurrentPsm().getsFName());
				}
				if(":getCurrentDateTime()".equals(rowValue.get(col))) {
					rowValue.put(col, Utils.getCurrentDateTime());
				}
				if(":getCurrentPersonCode()".equals(rowValue.get(col))) {
					rowValue.put(col, SecurityService.getCurrentPerson().getString("cUsercode"));
				}
				if(":getCurrentPersonName()".equals(rowValue.get(col))) {
					rowValue.put(col, SecurityService.getCurrentPerson().getString("cUsername"));
				}
				if(":getCurrentPersonID()".equals(rowValue.get(col))) {
					rowValue.put(col, SecurityService.getCurrentPerson().getString("userId"));
				}
				if(":getCurrentOgnFID()".equals(rowValue.get(col))) {
					rowValue.put(col, SecurityService.getCurrentOgn().getsFID());
				}
				if(":getCurrentOgnLongName()".equals(rowValue.get(col))) {
					rowValue.put(col, SecurityService.getCurrentOgn().getsLongName());
				}
				//System.out.println("controller.defaultValues-->>"+col+":"+rowValue.get(col));
			}
			
		}
//		System.out.println("data-->"+data.toJSONString());
		return data;
	}
	
	public static void setDataAccessUrls(Map<String,String> dataAccessUrls){
		getCurrentSession().setAttribute("dataAccessUrls",dataAccessUrls);
	}
	
	@SuppressWarnings("unchecked")
	public static List<String> getDataAccessIDs(){
		return (List<String>) getCurrentSession().getAttribute("dataAccessIDs");
	}
	
	public static void setDataAccessIDs(List<String> dataAccessIDs){
		getCurrentSession().setAttribute("dataAccessIDs",dataAccessIDs);
	}
	
	/*
	public static Map<String, String> getCurrentLoginfo() {
		Map<String,String> map = new HashMap<String,String>();
		
		String id = Utils.getUUID();
		String cUsercode = SecurityService.getCurrentPerson().getString("cUsercode");
		String cUsername = SecurityService.getCurrentPerson().getString("cUsername");
		String userId = SecurityService.getCurrentPerson().getString("userId");

		String employeeNo = SecurityService.getCurrentPsm().getsFID();
		String employeeName = SecurityService.getCurrentPsm().getsFName();
		
		String enterpriseNo = SecurityService.getCurrentOgn().getsFID();
		String enterpriseName = SecurityService.getCurrentOgn().getsLongName();
		
		map.put("id", id);
		map.put("cUsercode", cUsercode);
		map.put("cUsername", cUsername);
		map.put("userId", userId);
		map.put("employeeNo", employeeNo);
		map.put("employeeName", employeeName);
		map.put("enterpriseNo", enterpriseNo);
		map.put("enterpriseName", enterpriseName);
		map.put("orderDate", Utils.getCurrentDate().toString());
		map.put("cDatetime", Utils.getCurrentDateTime().toString());
		
		return map;
	}
	*/
	
	/*
	public static Map<String,String> getRestfulLoginfo(HttpServletRequest request) {
		
		Map<String,String> map = new HashMap<String,String>();
		SaOpperson person = (SaOpperson) request.getAttribute("person");
		
		String id = Utils.getUUID();
		String cUsercode = person.getsCode();
		String cUsername = person.getsName();
		String userId = person.getsID();

		String employeeNo = null;
		String employeeName = null;
		
		String enterpriseNo = null;
		String enterpriseName = null;
			
		map.put("id", id);
		map.put("cUsercode", cUsercode);
		map.put("cUsername", cUsername);
		map.put("userId", userId);
		map.put("employeeNo", employeeNo);
		map.put("employeeName", employeeName);
		map.put("enterpriseNo", enterpriseNo);
		map.put("enterpriseName", enterpriseName);
		map.put("orderDate", SystemService.getCurrentDate().toString());
		map.put("cDatetime", SystemService.getCurrentDateTime().toString());
		
		return map;
	}
	*/

}
